/*
 * @lc app=leetcode.cn id=752 lang=cpp
 *
 * [752] 打开转盘锁
 */

// @lc code=start
class Solution {
public:
    int openLock(vector<string>& deadends, string target) {
        if (target == "0000") return 0;
        unordered_set<string> seen(deadends.begin(), deadends.end());
        if (seen.count("0000")) return -1;

        auto num_pre = [](char x) -> char {
            return x == '0' ? '9' : x - 1;
        };

        auto num_succ = [](char x) -> char {
            return x == '9' ? '0' : x + 1;
        };

        auto get = [&](string& status) -> vector<string> {
            vector<string> ret;
            for (int i = 0; i < 4; ++i) {
                char num = status[i];
                status[i] = num_pre(num);
                ret.emplace_back(status);
                status[i] = num_succ(num);
                ret.emplace_back(status);
                status[i] = num;
            }
            return ret;
        };

        queue<string> que;
        que.emplace("0000");
        int step = 1;
        while (!que.empty()) {
            int sz = que.size();
            for (int j = 0; j < sz; ++j) {
                string cur = que.front();
                que.pop();
                for (auto& next_status : get(cur)) {
                    if (!seen.count(next_status)) {
                        if (next_status == target) return step;
                        que.emplace(next_status);
                        seen.emplace(next_status);
                    }
                }
            }
            step++;
        } 
        return -1;
    }
};
// @lc code=end

